from flask import Flask, request, jsonify
import time,threading as thd,json,public_lib
import logging
from werkzeug.serving import make_server
public_lib.run_path(__file__)
webapi_received = {}   # 接收到的字典数据
webapi_send = {}       # 发送的字典数据
webapi_path_recevied ='/post'
webapi_path_send = '/get'
webapiName = __name__
webapi_received_en = False
webapi_rec_done = False
app = Flask(webapiName)
# 设置日志级别
log = logging.getLogger('werkzeug')
log.setLevel(logging.CRITICAL)
app.config['JSON_AS_ASCII'] = False
# 实现全局变量，其他py文件可以访问
@app.route('/', methods=["GET", "POST"])
def index():
       return 'welcom to web api'
# 模拟数据库
@app.route(webapi_path_recevied, methods=['POST'])
def store_dict():
    global webapi_received_en,webapi_received,webapi_rec_done
    # 获取请求中的JSON数据
    try:
        recData = request.data
        data = json.loads(recData)
    except Exception as e:
        return jsonify({"error": f"数据格式有误->{e}"}), 400
    # 检查数据是否为字典
    if not isinstance(data, dict):
        return jsonify({"error": "输入json数据格式错误，请检查"}), 400
    # 存储字典数据
    webapi_received.update(data)
    webapi_received_en = True
    # 接收成功后反馈信息
    return jsonify({"rec_message": 1}), 200
@app.route(webapi_path_send, methods=['GET'])
def get_dicts():
    global webapi_send
    # 发送存储的所有字典数据
    return jsonify(webapi_send), 200
# 启动http服务
def app_run(ip='127.0.0.1',port=5000):
    def run_server(ip='127.0.0.1',port=5000):
        global http_server
        http_server = make_server(ip, port, app)
        # print(f"web api is running on http://{ip}:{port}")
        http_server.serve_forever()
    thd0 =thd.Thread(target=run_server,args=(ip,port))
    thd0.daemon = True
    thd0.start()
# 关闭http服务
def app_close():
    http_server.shutdown()
def main_run(ip='127.0.0.1',port=5000):
    app_run(ip,port)
    num = 0
    while 1:
        if num == 10:
            app_close()
        time.sleep(1)
        if num > 20:
            pass
            num = 0
            app_run(ip,port)
        num += 1
        # print(f"web api is running{num}")
    else:
        app_close()
if __name__ == '__main__':
    main_run()
